/*
 * BaseFileCallBack.java
 * business
 *
 * Created by ChenTao on 2017/3/7.
 *
 * Copyright (c) 2017年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.data.net;

import com.lzy.okgo.callback.FileCallback;
import com.yidiandao.business.data.net.exception.NetErrorHelper;
import com.yidiandao.business.data.net.exception.NetErrorInfo;
import com.yidiandao.business.utils.UIUtils;

import java.io.File;

import okhttp3.Call;
import okhttp3.Response;

/**
 * BaseFileCallBackHelper
 * <p>
 * <p>Created by ChenTao(chentao7v@gmail.com) on 2017/3/7 16:44
 */
public class BaseFileCallBack extends FileCallback {

    private DownloadListener mListener;

    private String mUrl;

    private BaseRequest mRequest;

    public BaseFileCallBack(
            BaseRequest request,
            String destFileDir,
            String destFileName,
            DownloadListener listener) {
        // 指定下载的目录
        super(destFileDir, destFileName);

        mRequest = request;
        mUrl = request.getUrl();
        mListener = listener;
    }

    @Override
    public void onSuccess(File file, Call call, Response response) {
        if (mListener != null) {
            mListener.onSuccess(file);
        }
    }

    @Override
    public void onError(Call call, Response response, Exception e) {
        // 网络相关错误(无网络连接，Json转换异常等) 处理
        // 包括上传友盟,前台打印错误信息

        // 网络错误封装
        NetErrorInfo netErrorInfo = NetErrorHelper.generateNetErrorInfo(e);

        if (mListener != null) {
            if (mListener.onError(netErrorInfo)) {
                // 给用户友好提示
                UIUtils.showToast(netErrorInfo.getMessage());
            }
        }

        // 打印错误到控制台,并上传部分错误到友盟
        NetErrorHelper.reportError(BaseFileCallBack.class, mUrl, mRequest, netErrorInfo, null);
    }

    @Override
    public void onAfter(File file, Exception e) {
        if (mListener != null) {
            mListener.onFinal();
        }
    }
}
